package com.system.demo.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import com.system.demo.commonService.RedisService;
import com.system.demo.entity.DTO.ForgetPassInfo;
import com.system.demo.entity.DTO.LoginInfo;
import com.system.demo.service.LoginService;
import com.system.demo.tool.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 类描述: 登录有关的controller
 * @since 1.0
 * @author luodeng
 */

@RestController
public class LoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private RedisService redisService;


    @GetMapping("login/captcha")
    public ResponseResult<Map<String, Object>> getCaptcha() {
        return loginService.getCaptcha();
    }

    @PostMapping("/login")
    public ResponseResult<?> login(@RequestBody LoginInfo loginInfo, @RequestParam String token) {
        return loginService.login(loginInfo, token);
    }

    @GetMapping("/logout")
    @SaCheckLogin
    public ResponseResult<?> logout(){
        return loginService.logout();
    }
    @GetMapping("/sendMail")
    ResponseResult<Map<String, Object>> sendMail(@RequestParam String emailReceiver){
        String lockKey = "lock:email:" + emailReceiver; // 基于 email 生成锁的 Key
        String lockValue = UUID.randomUUID().toString(); // 防止误删的唯一值
        long lockExpireTime = 60; // 锁的过期时间（秒）
        // 尝试获取锁
        if (redisService.tryLock(lockKey, lockValue, lockExpireTime)) {
            try {
                return loginService.sendMail(emailReceiver);
            } catch (Exception e) {
                return ResponseResult.InternalServerError("服务器内部错误 请稍后再试");
            }
        } else {
            return ResponseResult.BadRequest("发邮件不要钱啊？？？别急嘛");
        }
    }

    @PostMapping("/forgetPass")
    public ResponseResult<Map<String, Object>> forgetPass(@RequestBody ForgetPassInfo forgetPassInfo, @RequestParam String token){
        return loginService.forgetPass(forgetPassInfo, token);
    }

}
